﻿//  --------------------------------
//  Copyright (c) 2010 Michael Schuler, Sascha Burger. All rights reserved.
//  This source code is made available under the terms of the Microsoft Public License (Ms-PL)
//  http://p2pmessaging.codeplex.com/license
//  ---------------------------------
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Mail;
using System.Text;
using p2pMessaging.Interfaces;

namespace p2pMessaging.BL.Plugin
{
	/// <summary>
	/// Plugin to send emails. It's not possible to receive emails.
	/// </summary>
	public sealed class EmailMessageService : IMessageService
	{
		private static readonly Guid myPluginId = new Guid("6880790A-FC9E-4CB8-A5E4-B35F502B8B0A");

		/// <summary>
		/// Gets the id of the Plugin.
		/// </summary>
		public Guid PluginId
		{
			get { return myPluginId; }
		}

		/// <summary>
		/// Send a new email.
		/// </summary>
		/// <param name="message">Message to send as email.</param>
		public void Send(IMessage message)
		{
			if (message == null)
			{
				throw new ArgumentNullException("message");
			}

			message.PluginId = myPluginId;

			SmtpClient client = new SmtpClient();
			client.Credentials = new NetworkCredential("p2ptest@michaelschuler.ch", "987abc123");
			client.EnableSsl = false;
			client.Host = "mail.michaelschuler.ch";
			client.Port = 25;

			MailMessage mail = getMessage(message);
			
			//client.Send(mail);
		}

		/// <summary>
		/// Not implemented, returns an empty list.
		/// </summary>
		/// <returns>Empty list.</returns>
		public List<IMessage> Receive()
		{
			return new List<IMessage>(0);
		}

		/// <summary>
		/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
		/// </summary>
		/// <filterpriority>2</filterpriority>
		public void Dispose()
		{
		}
		
		private static MailMessage getMessage(IMessage message)
		{
			MailMessage mm = new MailMessage();
			mm.Body = message.Data;
			mm.BodyEncoding = Encoding.UTF8;
			mm.From = new MailAddress(message.Sender.EmailAddress, message.Sender.DisplayName, Encoding.UTF8);
			mm.Subject = message.Subject;
			mm.SubjectEncoding = Encoding.UTF8;
			message.Recipient.ForEach(r => mm.To.Add(r.EmailAddress));
			return mm;
		}
	}
}
